<template>
  <div class="createPost-container">

    <sticky :className="'sub-navbar'" :z-index="$upZindex">

      <el-button v-if="opt!='info'" v-loading="loading" style="margin-left: 10px;" type="success" @click="createData">{{$t('table.submit')}}
      </el-button>

      <el-button v-if="opt=='info'" v-loading="loading" style="margin-left: 10px;" type="success" @click="back">{{$t('table.back')}}
      </el-button>

    </sticky>


    <el-form class="form-container" :model="postForm" :rules="rules" ref="postForm" label-position="right" label-width="150px" style='width: 60%; margin-left:10px;margin-top:20px;'>
      <div class="divide-line">作品信息</div>

      <el-form-item label="主键" prop="supplyId" hidden="true">
        {{postForm.supplyId}}
      </el-form-item>
      <el-form-item label="作品名称" prop="worksName">
        {{postForm.worksName}}
      </el-form-item>

      <el-form-item label="作品背景" prop="background">
        <el-tag v-if="postForm.background && postForm.background!=''" v-for="(item,index) in postForm.background"  :key="index">{{item | $backgroundFilter}}</el-tag>
      </el-form-item>

      <el-form-item label="作品类型" prop="worksType">
        {{postForm.worksType | $worksTypeFilter}}
      </el-form-item>
      <!-- 绘本单品内容 -->
      <div v-if="postForm.worksType=='WorksSingle'">
        <el-form-item label="ISBN号" prop="isbnNo">
          {{postForm.isbnNo}}
        </el-form-item>
        <el-form-item label="出版社" prop="publishingName">
          {{postForm.publishingName}}
        </el-form-item>
        <el-form-item label="文字作者" prop="authorName">
          {{postForm.authorName}}
        </el-form-item>
        <el-form-item label="绘者" prop="pictureAuthorName">
          {{postForm.pictureAuthorName}}
        </el-form-item>
        <el-form-item label="译者" prop="translatorName">
          {{postForm.translatorName}}
        </el-form-item>
        <el-form-item label="系列名称" prop="seriesName">
          {{postForm.seriesName}}
        </el-form-item>
        <el-form-item label="出版日期" prop="publicationDate">
            {{postForm.publicationDate}}
        </el-form-item>
      </div>
      <!-- 绘本单品内容 -->
      <!-- 听书合辑内容 -->
      <div v-if="postForm.worksType=='ListeningCollection'">
        <el-form-item label="主播" prop="anchorName">
          {{postForm.anchorName}}
        </el-form-item>
        <el-form-item label="集数" prop="seriesNum">
          {{postForm.seriesNum}}
        </el-form-item>
      </div>
      <el-form-item label="定价" prop="worksPrice">
        {{postForm.worksPrice}}
      </el-form-item>
      <!-- 听书合辑内容 -->
      <el-form-item label="作品简介" prop="worksIntroduction">
        {{postForm.worksIntroduction}}
      </el-form-item>
      <el-form-item label="作者简介" prop="authorIntroduction">
        {{postForm.authorIntroduction}}
      </el-form-item>

      <el-form-item label="内容状况" prop="contentStatus">
        {{postForm.contentStatus | $tfFilter}}
      </el-form-item>

      <div class="divide-line">版权信息</div>

      <el-form-item hidden="true" label="供应商id" prop="supplyId">
        {{postForm.supplyId}}
      </el-form-item>

      <el-form-item label="合同编号" prop="contractNo">
        {{postForm.contractNo}}
      </el-form-item>

      
      <el-form-item label="所授权利" prop="copyrightClass">
        <el-tag v-for="(item,index) in postForm.copyrightClass" type="success" :key="index">{{item | $copyrightClassFilter}}</el-tag>
      </el-form-item>


      <el-form-item label="是否独家授权" prop="soleFlag">
        {{postForm.soleFlag | $ynFilter}}

      </el-form-item>
      <el-form-item label="有无转授权" prop="subRightsFlag">
        {{postForm.subRightsFlag | $tfFilter}}
      </el-form-item>
      <el-form-item label="有无补协议" prop="protocolFlag">
        {{postForm.protocolFlag | $tfFilter}}
      </el-form-item>
      <el-form-item label="上线状态" prop="onlineStatus">
        {{postForm.onlineStatus | $onlineStatusFilter}}
      </el-form-item>
      <el-form-item label="开始时间" prop="beginDate">
          {{postForm.beginDate | $dateConvert}}
      </el-form-item>
      <el-form-item label="终止时间" prop="endDate">
          {{postForm.endDate | $dateConvert}}
      </el-form-item>
      <el-form-item label="权限使用范围" prop="copyrightsRange">
        <el-tag v-for="(item,index) in postForm.copyrightsRange" :key="index">{{item | $copyrightsRangeFilter}}</el-tag>
      </el-form-item>

      <el-form-item label="使用平台" prop="usedPlatform">
        <el-tag v-for="(item,index) in postForm.usedPlatform" :key="index">{{item | $usedPlatformFilter}}</el-tag>
      </el-form-item>
      <el-form-item label="原始版权" prop="originalCopyrightsFlag">
        {{postForm.originalCopyrightsFlag | $provideFilter}}
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        {{postForm.remark}}
      </el-form-item>

      <div class="divide-line">结算信息</div>

      <el-form-item label="结算形式" prop="balanceType">
        {{postForm.balanceType | $balanceTypeFilter}}
      </el-form-item>


      <el-form-item :label="amountLabelMap[this.postForm.balanceType]" v-if="postForm.balanceType!='DIVIDE'" prop="balance">
        {{postForm.balance}}
      </el-form-item>

      <div v-if="postForm.balanceType!='BUY'">
        <el-form-item label="甲方比例" prop="partyOneNum">
          {{postForm.partyOneNum}}
        </el-form-item>
        <el-form-item label="乙方比例" prop="partyTwoNum">
          {{postForm.partyTwoNum}}
        </el-form-item>
        <el-form-item v-if="postForm.partyThreeNum" label="丙方比例" prop="partyThreeNum">
          {{postForm.partyThreeNum}}
        </el-form-item>
      </div>
      <el-form-item label="结算说明" prop="balanceRemark">
        {{postForm.balanceRemark}}
      </el-form-item>




    </el-form>

    <div v-if="opt=='info'">
      <div class="divide-line-long">合同信息</div>
      <SupplyContractList :copyrightsId="postForm.id"></SupplyContractList>


      <div v-if="postForm.worksStatus == 'VALID'" style="margin-bottom: 30px" align="center">
          <el-button v-has="'copyrightsTable_edit'" type="primary" size="large" @click="handleUpdate">{{$t('table.edit')}}版权信息</el-button>
          <el-button v-has="'copyrightsTable_disable'" type="danger" size="large" @click="handleInvalid">{{$t('table.invalid')}}</el-button>
      </div>
    </div>

  </div>

</template>

<script>
  import Sticky from '@/components/Sticky' // 粘性header组件
  import { infoCopyrights, createCopyrights, updateCopyrights, invalidCopyrights } from '@/api/copyrights/copyrights'
  import { fetchSupplyList, checkContractDate, fetchContractList } from '@/api/supplyContract/supplyContract'

  import SupplyContractList from '@/views/components/SupplyContractList'

  const defaultForm = {
    code: ''
  }

  export default {
    name: 'copyrightAdd',
    components: { Sticky, SupplyContractList },
    data() {
      return {
        postForm: Object.assign({
          balanceType: 'BUY',
          contractType: 'IN',
          contractNum: '2',
          contractNo: '',
          copyrightsRange: [],
          usedPlatform: [],
          background: []
        }, defaultForm),
        loading: false,
        rules: {
        },
        listQuery: {
          compoundSearch: undefined,
          expireStatus: undefined,
          clearMethod: undefined,
          contractType: undefined
        },
        copyrightsRangeKeyOptions: ['OVERSEAS', 'MAINLAND', 'GAT'],
        amountLabelMap: {
          BUY: '买断金额',
          PrePayDivide: '预付金额',
          MixClear: '涉及金额',
          DIVIDE: '无金额'
        },
        disabled: false,
        opt: '',
        range_org: {},
        platform_org: {},
        background_org: {}
      }
    },
    computed: {
      contentShortLength() {
        return this.postForm.content_short.length
      }
    },
    created() {
      const id = this.$route.query.id
      const copyrightsNo = this.$route.query.copyrightsNo
      if (id != null || copyrightsNo != null) {
        const params = { 'id': id, 'copyrightsNo': copyrightsNo }
        infoCopyrights(params).then(response => {
          if (response.success) {
            this.postForm = Object.assign({}, response.content) // copy obj
            // 作品背景
            const backgroundstr = response.content.background
            const background = []
            if (backgroundstr) {
              const backgrounds = backgroundstr.split(',')
              for (var item in backgrounds) {
                background.push(backgrounds[item])
              }
            }
            this.postForm.background = background
            // 权限使用范围选中状态
            const rangestr = response.content.copyrightsRange
            const copyrightsRange = []
            if (rangestr) {
              const ranges = rangestr.split(',')
              for (var range in ranges) {
                copyrightsRange.push(ranges[range])
              }
            }
            this.postForm.copyrightsRange = copyrightsRange
            // 所授权利
            const copyrightClassstr = response.content.copyrightClass
            const copyrightClass = []
            if (copyrightClassstr) {
              const copyrightClasses = copyrightClassstr.split(',')
              for (var item_k in copyrightClasses) {
                copyrightClass.push(copyrightClasses[item_k])
              }
            }
            this.postForm.copyrightClass = copyrightClass
            // 使用平台选中状态
            const platformstr = response.content.usedPlatform
            const usedPlatform = []
            if (platformstr) {
              const platforms = platformstr.split(',')
              for (var platform in platforms) {
                usedPlatform.push(platforms[platform])
              }
            }
            this.postForm.usedPlatform = usedPlatform
            // 记录老合同号用于比较
            this.oldContractInNo = this.postForm.contractInNo
            // 判断是否是详情页面
            this.opt = this.$route.query.opt
            if (this.opt === 'info') {
              this.disabled = true
              this.range_org = this.postForm.copyrightsRange
              this.platform_org = this.postForm.usedPlatform
              this.background_org = this.postForm.background
            }
          } else {
            this.$message({
              type: 'fail',
              message: response.message
            })
            this.$router.go(-1)
          }
        })
      }
    },
    filters: {

    },
    methods: {
      submitForm() {},
      createData() {
        this.$refs['postForm'].validate((valid) => {
          if (valid) {
            const background = this.postForm.background
            const copyrightsRange = this.postForm.copyrightsRange
            const usedPlatform = this.postForm.usedPlatform
            var copyrightsRange_sub = ''
            var usedPlatform_sub = ''
            var background_sub = ''
            // 拼接作品背景
            for (var i = 0; i < background.length; i++) {
              var item = background[i]
              if (item !== 'true') {
                background_sub += item
                if (i !== background.length - 1) {
                  background_sub += ','
                }
              }
            }
            // 拼接权限使用范围
            for (var j = 0; j < copyrightsRange.length; j++) {
              var item_j = copyrightsRange[j]
              if (item_j !== 'true') {
                copyrightsRange_sub += item_j
                if (j !== copyrightsRange.length - 1) {
                  copyrightsRange_sub += ','
                }
              }
            }
            // 拼接使用平台
            for (var k = 0; k < usedPlatform.length; k++) {
              var item_k = usedPlatform[k]
              if (item_k !== 'true') {
                usedPlatform_sub += item_k
                if (k !== usedPlatform.length - 1) {
                  usedPlatform_sub += ','
                }
              }
            }

            Object.assign(this.postForm, { 'background': background_sub })
            Object.assign(this.postForm, { 'copyrightsRange': copyrightsRange_sub })
            Object.assign(this.postForm, { 'usedPlatform': usedPlatform_sub })

            // 根据是否有id来判断
            if (this.postForm.id != null) {
              updateCopyrights(this.postForm).then(response => {
                if (response.success) {
                  this.$notify({
                    title: '成功',
                    message: '更新成功',
                    type: 'success',
                    duration: 2000
                  })
                  this.$router.push({ name: 'copyrightsTable' })
                } else {
                  this.$message({
                    type: 'fail',
                    message: response.message
                  })
                }
              })
            } else {
              createCopyrights(this.postForm).then((response) => {
                if (response.success) {
                  this.$notify({
                    title: '成功',
                    message: '创建成功',
                    type: 'success',
                    duration: 2000
                  })
                  this.$router.push({ name: 'copyrightsTable' })
                } else {
                  this.$message({
                    type: 'fail',
                    message: response.message
                  })
                }
              })
            }
            this.postForm.background = background
            this.postForm.copyrightsRange = copyrightsRange
            this.postForm.usedPlatform = usedPlatform
          }
        })
      },
      querySearchAsync(queryString, callback) {
        var list = [{}]
        // 调用的后台接口
        // let url = 后台接口地址 + queryString;
        // 从后台获取到对象数组
        const params = { 'abbreviation': queryString }

        fetchSupplyList(params).then((response) => {
          if (response.success) {
            // 在这里为这个数组中每一个对象加一个value字段, 因为autocomplete只识别value字段并在下拉列中显示
            for (const i of response.content) {
              // 将名字放入
              Object.assign(i, { 'value': i.abbreviation })
            }
            list = response.content
            callback(list)
          } else {
            this.$message({
              type: 'fail',
              message: response.message
            })
          }
        }).catch((error) => {
          console.log(error)
        })
      },
      // 供应商选择后的回调
      handleSelect(item) {
        // 供应商id
        this.postForm.supplyId = item.id
      },
      // 合同编号选择
      queryContractIn(queryString, callback) {
        var list = [{}]
        // 调用的后台接口
        // let url = 后台接口地址 + queryString;
        // 从后台获取到对象数组
        const params = { 'contractNo': this.postForm.contractNo }

        fetchContractList(params).then((response) => {
          if (response.success) {
            // 在这里为这个数组中每一个对象加一个value字段, 因为autocomplete只识别value字段并在下拉列中显示
            for (const i of response.content) {
              // 将名字放入
              Object.assign(i, { 'value': i.contractNo })
            }
            list = response.content
            callback(list)
          } else {
            this.$message({
              type: 'fail',
              message: response.message
            })
          }
        }).catch((error) => {
          console.log(error)
        })
      },
      // 合同选择后的回调
      handleContractSelect(item) {
        // 赋值
        this.postForm.beginDate = item.beginDate
        this.postForm.endDate = item.endDate
        this.postForm.balanceType = item.balanceType
        this.postForm.balance = item.totalAmount
        this.postForm.partyOne = item.partyOne
        this.postForm.partyOneNum = item.partyOneNum
        this.postForm.partyTwo = item.partyTwo
        this.postForm.partyTwoNum = item.partyTwoNum
        this.postForm.partyThree = item.partyThree
        this.postForm.partyThreeNum = item.partyThreeNum
        this.postForm.balanceRemark = item.balanceRemark
        this.postForm.supplyId = item.supplyId
        this.postForm.contractNum = item.contractNum
      },
      checkContractDate() {
        if (this.postForm.contractInNo == null || this.postForm.contractInNo === '' || this.postForm.contractInNo === this.oldContractInNo) {
          return
        }
        const params = { 'contractNo': this.postForm.contractInNo }

        checkContractDate(params).then((response) => {
          if (response.success) {
            // 在这里为这个数组中每一个对象加一个value字段, 因为autocomplete只识别value字段并在下拉列中显示
            if (!response.success) {
              this.$message(response.message)
              this.postForm.contractInNo = ''
            }
          } else {
            this.$message({
              type: 'fail',
              message: response.message
            })
          }
        }).catch((error) => {
          console.log(error)
        })
      },
      // 返回
      back() {
        // this.$router.push({ name: 'copyrightsTable' })
        history.go(-1)
      },
      keepOriginCheckBox() {
        if (this.opt === 'info') {
          this.postForm.copyrightsRange = this.range_org
          this.postForm.usedPlatform = this.platform_org
        }
      },
      handleUpdate() {
        this.$router.push({ name: 'copyrightsEdit', query: { id: this.postForm.id }})
      },
      handleInvalid() {
        this.$confirm('失效后，该条数据不可操作，确认失效?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then((response) => {
          // 调用失效接口
          var p = { id: this.postForm.id }
          invalidCopyrights(p).then(response => {
            if (response.success) {
              this.$message({
                type: 'success',
                message: '操作成功!'
              })
              this.$router.push({ name: 'copyrightsTable' })
            } else {
              this.$message({
                type: 'fail',
                message: response.message
              })
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消操作'
          })
        })
      }
    },
    watch: {
      '$route'(to, from) {
        if (from.name === 'copyrightsInfo') {
          this.$router.go(0)
        }
      }
    }
  }
</script>



